﻿#include <QFileDialog>
#include <QMessageBox>
#include <QDebug>
#include <QDateTime>

#include "adifeye.h"
#include "ui_adifeye.h"

Adifeye::Adifeye(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::Adifeye)
{
    ui->setupUi(this);
    ui->QSO_VIEW->setColumnCount(14);
    ui->QSO_VIEW->setAlternatingRowColors(true);
    ui->QSO_VIEW->horizontalHeader()->setDefaultAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    //ui->QSO_VIEW->setStyleSheet("QTableWidget::item {text-align: center;}");
    for (int y = 0; y< 14 ; ++y) {
        ui->QSO_VIEW->setColumnWidth(y,76);
    }
    ui->QSO_VIEW->setHorizontalHeaderLabels(QStringList()
                                            <<"对方呼号"<<"位置网格"<<"波段"
                                            <<"频率"<<"通信模式"<<"对方信号"
                                            <<"己方信号"<<"通联日期"<<"开始时间"
                                            <<"结束日期"<<"结束时间"<<"我方呼号"
                                            <<"我方位置"<<"发射功率");
}

Adifeye::~Adifeye()
{
    delete ui;
    delete allRecordInFile;
}

bool Adifeye::readRecordSet()
{
    QByteArray date;//存读取的数据
    char chr;//由于switch只能判断数字，所以把读的数据转成ASCII
    QString tag;//保存标签
    QString value;//保存标签对应的值
    //QString tagLen;
    unsigned int tagLenght = 0;//保存标签值的字符长度
    records_count = 0;//清楚记录计数
    allRecordInFile = new QList<QSO_Fields>;
    clearQsoFiels();

    QFile f4r(aFileName);
    if(!f4r.open(QIODevice::ReadOnly))
    {
        qDebug()<<"打开文件失败：" << f4r.errorString();
        return false;
    }

    while (!f4r.atEnd())
    {
        //date = f4r.read(1);

        f4r.getChar(&chr);

        switch(QChar(chr).toLatin1())
        {
        case 60://读到"<"符号时
            tag.clear();
            tagLenght=0;
            f4r.getChar(&chr);
            tag.append(QChar(chr).toLower());
            break;
        case 62://读到">"符号时
            value.clear();
            if (tagLenght == 0 && tag == "eor")
            {
                allRecordInFile->append(record_info);
                clearQsoFiels();
                records_count += 1;
                tag.clear();
                break;
            }
            if(tagLenght > 0)
            {
                date = f4r.read(tagLenght);
                value.append(date.data());
                if(tag == "call"){ record_info.call = value;break;}
                else if(tag == "gridsquare"){ record_info.gridsquare= value;break;}
                else if(tag == "band"){ record_info.band = value;break;}
                else if(tag == "freq"){ record_info.freq = value;break;}
                else if(tag == "mode"){ record_info.mode = value;break;}
                else if(tag == "rst_rcvd"){ record_info.rst_rcvd = value;break;}
                else if(tag == "rst_sent"){ record_info.rst_sent = value;break;}
                else if(tag == "qso_date"){ record_info.qso_date = value;break;}
                else if(tag == "time_on"){ record_info.time_on = value;break;}
                else if(tag == "qso_date_off"){ record_info.qso_date_off = value;break;}
                else if(tag == "time_off"){ record_info.time_off = value;break;}
                else if(tag == "station_callsign"){ record_info.station_callsign = value;break;}
                else if(tag == "my_gridsquare"){ record_info.my_gridsquare = value;break;}
                else if(tag == "tx_pwr"){ record_info.tx_pwr = value;break;}
                break;
            };
            //QMessageBox::warning(this,"发现错误","字段长度为0");
            break;
        case 58://读到"："符号时
            /*
             * 注意：这里只读了一位数字，若字段长度超过1位数这里会出问题。<<<<<<<<<<<<<
            */

        {

            int k = 0;
           do{
                ++k;
                f4r.getChar(&chr);
            }
            while (QChar(chr).toLatin1() != 62);

            f4r.seek(f4r.pos()-k);
            tagLenght = f4r.read(k-1).toUInt();
            break;
        }
        case 9://"/t"
            break;
        case 10://"/r"
            break;
        case 13://"/n"
            break;
        case 32://" "
            break;
        default:
            tag.append(QChar(chr).toLower());
            break;
        }

    };
    if(allRecordInFile->count() < 1 ) return false;
    all_QSO_count += records_count;
    ui->statusbar->clearMessage();
    ui->statusbar->showMessage(QString("本次读取QSO记录%1条。总共读取QSO记录%2条。").arg(records_count).arg(all_QSO_count));
    f4r.close();
    return true;
}

void Adifeye::clearQsoFiels()
{
    record_info.call = "";
    record_info.gridsquare= "";
    record_info.band = "";
    record_info.freq = "";
    record_info.mode = "";
    record_info.rst_rcvd = "";
    record_info.rst_sent = "";
    record_info.qso_date = "";
    record_info.time_on = "";
    record_info.qso_date_off = "";
    record_info.time_off = "";
    record_info.station_callsign = "";
    record_info.my_gridsquare = "";
    record_info.tx_pwr = "";
}

void Adifeye::on_pushButton_clicked()
{
    QString curPath=QDir::currentPath();//获取系统当前目录
    //获取应用程序的路径
    QString dlgTitle="选择一个文件"; //对话框标题
    QString filter="ADIF文件(*.adi);;所有文件(*.*)"; //文件过滤器
    aFileName=QFileDialog::getOpenFileName(this,dlgTitle,curPath,filter);

    if (aFileName.isEmpty())
    {
        QMessageBox::warning(this,"文件出错", "选择的文件是空的。");return;
    };
    if(readRecordSet())
    {

        int tmp = ui->QSO_VIEW->rowCount();
        ui->QSO_VIEW->setRowCount(tmp + records_count);

        for (int x = 0; x < records_count; ++x) {
            record_info = allRecordInFile->at(x);
            ui->QSO_VIEW->setItem(tmp+x,0,new QTableWidgetItem(record_info.call));
            ui->QSO_VIEW->setItem(tmp+x,1,new QTableWidgetItem(record_info.gridsquare));
            ui->QSO_VIEW->setItem(tmp+x,2,new QTableWidgetItem(record_info.band));
            ui->QSO_VIEW->setItem(tmp+x,3,new QTableWidgetItem(record_info.freq));
            ui->QSO_VIEW->setItem(tmp+x,4,new QTableWidgetItem(record_info.mode));
            ui->QSO_VIEW->setItem(tmp+x,5,new QTableWidgetItem(record_info.rst_rcvd));
            ui->QSO_VIEW->setItem(tmp+x,6,new QTableWidgetItem(record_info.rst_sent));
            ui->QSO_VIEW->setItem(tmp+x,7,new QTableWidgetItem(record_info.qso_date));
            ui->QSO_VIEW->setItem(tmp+x,8,new QTableWidgetItem(record_info.time_on));
            ui->QSO_VIEW->setItem(tmp+x,9,new QTableWidgetItem(record_info.qso_date_off));
            ui->QSO_VIEW->setItem(tmp+x,10,new QTableWidgetItem(record_info.time_off));
            ui->QSO_VIEW->setItem(tmp+x,11,new QTableWidgetItem(record_info.station_callsign));
            ui->QSO_VIEW->setItem(tmp+x,12,new QTableWidgetItem(record_info.my_gridsquare));
            ui->QSO_VIEW->setItem(tmp+x,13,new QTableWidgetItem(record_info.tx_pwr));
            for (int y = 0; y< 14 ; ++y) {
                ui->QSO_VIEW->item(tmp+x,y)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
            }
        }
        ui->QSO_VIEW->sortItems(9,Qt::DescendingOrder);
        //ui->QSO_VIEW->sortItems(10,Qt::DescendingOrder);
    }
    allRecordInFile->clear();
}

void Adifeye::on_pushButton_3_clicked()
{
    ui->QSO_VIEW->clearContents();
    ui->QSO_VIEW->setRowCount(0);
    records_count=0;
    all_QSO_count=0;
}

void Adifeye::on_pushButton_4_clicked()
{
    QApplication::exit();
}


void Adifeye::on_pushButton_2_clicked()
{
    if(ui->QSO_VIEW->rowCount()==0) return;

    QString curPath=QDir::currentPath();//获取系统当前目录
    //获取应用程序的路径
    QString dlgTitle="选择一个文件"; //对话框标题
    QString filter="ADIF文件(*.adi);;所有文件(*.*)"; //文件过滤器
    //aFileName=QFileDialog::getOpenFileName(this,dlgTitle,curPath,filter);
    aFileName = QFileDialog::getSaveFileName(this,dlgTitle,curPath,filter);

    QFile f4w(aFileName);
    if(!f4w.open(QIODevice::WriteOnly))
    {
        qDebug()<<"打开文件失败：" << f4w.errorString();
        return;
    }
//    ADIF Export
//    <adif_ver:5>3.1.1
//    <created_timestamp:15>20240113 145226
//    <programid:6>WSJT-X
//    <programversion:9>2.6.0-rc5
//    <eoh>
    QString timestamp = QDateTime::currentDateTime().toString("yyyymmdd hhMMss");
    QString file_header_txt =   "ADIF EYE Export\r\n"
                                "<adif_ver:5>3.1.4\r\n"
                                "<created_timestamp:%1>%2\r\n"
                                "<programid:8>ADIF EYE\r\n"
                                "<programversion:14>20240127_0.0.1\r\n<eoh>\r\n";
    f4w.write(file_header_txt.arg(timestamp.length()).arg(timestamp).toLatin1());
    int tmp_r = ui->QSO_VIEW->rowCount();
    int tmp_c = ui->QSO_VIEW->columnCount();

    QString tmp_str="";
    QString tmp_contents = "";
    int tmp_contents_len = 0;
    for (int r = 0; r < tmp_r; r++) {
        for (int c = 0; c < tmp_c;c++ ) {
            tmp_contents = ui->QSO_VIEW->item(r,c)->text();
            tmp_contents_len = tmp_contents.length();
            switch (c) {
            case 0:
                tmp_str = "<call:%1>%2 ";
                break;
            case 1:
                tmp_str = "<gridsquare:%1>%2 ";
                break;
            case 4:;
                tmp_str = "<mode:%1>%2 ";
                break;
            case 6:
                tmp_str = "<rst_sent:%1>%2 ";
                break;
            case 5:
                tmp_str = "<rst_rcvd:%1>%2 ";
                break;
            case 7:
                tmp_str = "<qso_date:%1>%2 ";
                break;
            case 8:
                tmp_str = "<time_on:%1>%2 ";
                break;
            case 9:
                tmp_str = "<qso_date_off:%1>%2 ";
                break;
            case 10:
                tmp_str = "<time_off:%1>%2 ";
                break;
            case 2:
                tmp_str = "<band:%1>%2 ";
                break;
            case 3:
                tmp_str = "<freq:%1>%2 ";
                break;
            case 11:
                tmp_str = "<station_callsign:%1>%2 ";
                break;
            case 12:
                tmp_str = "<my_gridsquare:%1>%2 ";
                break;
            case 13:
                tmp_str = "<tx_pwr:%1>%2 ";
                break;
            }
            f4w.write(tmp_str.arg(tmp_contents_len).arg(tmp_contents).toLatin1());
        }
        f4w.write(QByteArray("<eor>\r\n"));

    }
    f4w.close();
}

